<template>
  <div>
    <div class="crumbs">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item>
          <i class="el-icon-lx-cascades"></i>
          食物管理
        </el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <div class="container">
      <div class="handle-box">
        <el-select
          v-model="query.type"
          placeholder="食物类型"
          class="handle-select mr10"
        >
          <el-option label="全部类型" value="">全部类型</el-option>
          <el-option
            :label="item"
            :value="index"
            v-for="(item, index) in typeList"
            :key="index"
          ></el-option>
        </el-select>
        <el-input
          v-model="query.foodName"
          placeholder="食物名称"
          class="handle-input mr10"
        ></el-input>
        <el-button type="primary" @click="handleSearch"
          ><el-icon style="margin-right: 5px"> <Search /> </el-icon
          >搜索</el-button
        >
        <el-button type="primary" @click="handleAdd">添加食物</el-button>
        <el-button type="primary" @click="handleAddAll">批量导入食物</el-button>

        <el-popconfirm
          title="确定要删除选中食物？"
          confirm-button-text="确定"
          cancel-button-text="取消"
          @confirm="deleteAll"
        >
          <template #reference>
            <el-button type="danger">删除选中</el-button>
          </template>
        </el-popconfirm>
      </div>

      <el-table
        :data="tableData"
        border
        class="table"
        ref="multipleTable"
        header-cell-class-name="table-header"
        @selection-change="handleSelect"
        v-loading="loading"
      >
        <el-table-column type="selection" width="70" align="center" />
        <el-table-column label="序号" width="65" align="center" fixed>
          <template #default="scope">
            {{ scope.$index + 1 }}
          </template>
        </el-table-column>
        <el-table-column
          prop="foodName"
          label="食物名称"
          width="100"
          fixed
        ></el-table-column>
        <el-table-column label="封面图片" align="center" width="150">
          <template #default="scope">
            <el-image :src="scope.row.logoImg"></el-image>
          </template>
        </el-table-column>
        <el-table-column label="食物分类" align="center" width="150">
          <template #default="scope">
            <el-tag :type="scope.row.type == '0' ? 'danger' : 'success'">
              {{ handleCategory(scope.row.type) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="食物状态" align="center" width="100">
          <template #default="scope">
            <el-tag
              :type="
                scope.row.unit == '0'
                  ? 'success'
                  : scope.row.unit == '1'
                  ? 'success'
                  : scope.row.unit == '2'
                  ? 'danger'
                  : ''
              "
            >
              {{
                scope.row.unit == '0'
                  ? '固体'
                  : scope.row.unit == '1'
                  ? '液体'
                  : '未知'
              }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          prop="protein"
          label="蛋白质(g)"
          align="center"
          width="90"
        ></el-table-column>
        <el-table-column
          prop="fat"
          label="脂肪(g)"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="carbohydrate"
          label="碳水(g)"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="caloric"
          label="热量(千卡)"
          width="100"
          align="center"
        ></el-table-column>
        <el-table-column
          label="不溶性膳食纤维(g)"
          prop="fiber"
          width="150"
          align="center"
        >
          <template #default="scope">
            <span v-if="scope.row.fiber === ''||scope.row.fiber==null">无</span>
            <span v-else>{{ scope.row.fiber }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="胆固醇(mg)"
          prop="cholesterol"
          width="100"
          align="center"
        >
          <template #default="scope">
            <span v-if="scope.row.cholesterol === ''||scope.row.cholesterol==null">无</span>
            <span v-else>{{ scope.row.cholesterol }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="维生素A(ugRAE)"
          prop="vitamina"
          width="140"
          align="center"
        >
          <template #default="scope">
            <span v-if="scope.row.vitamina === ''||scope.row.vitamina==null">无</span>
            <span v-else>{{ scope.row.vitamina }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="维生素C(mg)"
          prop="vitaminc"
          width="120"
          align="center"
        >
          <template #default="scope">
            <span v-if="scope.row.vitaminc === ''||scope.row.vitaminc==null">无</span>
            <span v-else>{{ scope.row.vitaminc }}</span>
          </template>
        </el-table-column>
        <el-table-column label="钙(mg)" prop="calcium" align="center">
          <template #default="scope">
            <span v-if="scope.row.calcium === ''||scope.row.calcium==null">无</span>
            <span v-else>{{ scope.row.calcium }}</span>
          </template>
        </el-table-column>
        <el-table-column label="钾(mg)" prop="potassium" align="center">
          <template #default="scope">
            <span v-if="scope.row.potassium === ''||scope.row.potassium==null">无</span>
            <span v-else>{{ scope.row.potassium }}</span>
          </template>
        </el-table-column>
        <el-table-column label="钠(mg)" prop="sodium" align="center">
          <template #default="scope">
            <span v-if="scope.row.sodium === ''||scope.row.sodium==null">无</span>
            <span v-else>{{ scope.row.sodium }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="食物血糖生成指数"
          prop="givalue"
          width="140"
          align="center"
        >
          <template #default="scope">
            <el-tag :type="tagType(scope.row.givalue)">
              {{
                scope.row.givalue === '' ||
                scope.row.givalue === 'null' ||
                scope.row.givalue === null
                  ? '无'
                  : scope.row.givalue
              }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" align="center">
          <template #default="scope">
            <el-button
              type="text"
              icon="el-icon-edit"
              @click="handleEdit(scope.$index, scope.row)"
              ><el-icon style="margin-right: 5px"> <Edit /> </el-icon
              >编辑</el-button
            >
            <el-popconfirm
              title="确定要删除此食物？"
              confirm-button-text="确定"
              cancel-button-text="取消"
              @confirm="handleDelete(scope.$index, scope.row)"
            >
              <template #reference>
                <el-button size="small" type="danger"
                  ><el-icon style="margin-right: 5px"> <Delete /> </el-icon
                  >删除</el-button
                >
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination">
        <el-pagination
          v-if="totalCount"
          v-model:currentPage="query.currentPage"
          v-model:page-size="query.pageSize"
          layout="prev, pager, next, jumper"
          :total="totalCount"
          @current-change="handleCurrentChange(query.currentPage)"
        />
      </div>
    </div>
  </div>
</template>
<script>
import { ref, reactive } from 'vue'
import request from '../../utils/request'
import { ElNotification, ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'
import qs from 'qs'

export default {
  setup() {
    const router = useRouter()

    const loading = ref(true)

    const resetForm = (formEl) => {
      if (!formEl) return
      formEl.resetFields()
    }
    // 处理添加方法的参数数据
    const processFormData = () => {
      const formData = new FormData()
      formData.append('foodId', ruleForm.foodId)
      formData.append('foodName', ruleForm.foodName)
      formData.append('protein', Number(ruleForm.protein))
      formData.append('fat', Number(ruleForm.fat))
      formData.append('carbohydrate', Number(ruleForm.carbohydrate))
      formData.append('caloric', Number(ruleForm.caloric))
      formData.append('type', ruleForm.type)
      if (selectedFile.value) {
        const fileName = selectedFile.value.name
        formData.append('avator', selectedFile.value, fileName)
      } else {
        formData.append('avator', ruleForm.avator)
      }
      if (ruleForm.desc) {
        formData.append('desc', ruleForm.desc)
      }

      return formData
    }

    const submitForm = async (formEl) => {
      if (!formEl) return
      const formData = processFormData()
      await formEl.validate((valid, fields) => {
        if (valid) {
          request
            .request({
              url: '/food/updateFood',
              method: 'post',
              data: formData,
            })
            .then((res) => {
              if (res.data.code == 200) {
                ElNotification({
                  title: '更新成功',
                  message: '成功更新食物信息',
                })

                getData()
                centerDialogVisible.value = false
                router.go(0)
              } else {
                ElNotification({
                  title: '更新失败',
                  message: '请联系管理员检查失败原因',
                })
              }
            })
            .catch((e) => {
              ElNotification({
                title: '更新失败',
                message: '请联系管理员检查失败原因',
              })
            })
        } else {
          ElNotification({
            title: '校验失败',
            message: '请重新填写信息',
          })
        }
      })
    }
    const ruleForm = reactive({
      foodId: '',
      type: 0,
      foodName: '',
      protein: '',
      fat: '',
      carbohydrate: '',
      caloric: '',
      desc: '',
      avator: '',
      unit: 0,
    })

    const typeList = [
      '其他',
      '谷类及制品',
      '薯类、淀粉及制品',
      '干豆类及制品',
      '蔬菜类及制品',
      '菌藻类',
      '水果类及制品',
      '坚果、种子类',
      '植物油',
      '畜肉类及制品',
      '禽肉类及制品',
      '乳类及制品',
      '蛋类及制品',
      '鱼虾蟹贝类',
      '油脂',
      '婴幼儿食品',
      '小吃、甜饼',
      '速食食品',
      '饮料类',
      '含酒精饮料',
      '糖、果脯和蜜饯、蜂蜜类',
      '调味品类',
    ]
    const ruleFormRef = ref()
    const centerDialogVisible = ref(false)
    const query = reactive({
      address: '',
      foodName: '',
      currentPage: 1,
      pageSize: 5,
    })
    const tableData = ref([])
    const totalCount = ref(0)

    // 获取表格数据
    const getData = () => {
      request
        .request({
          url: '/food/getFoodsByPageAndCondition',
          params: {
            type: query.type,
            foodName: query.foodName,
            currentPage: query.currentPage,
            pageSize: query.pageSize,
          },
          method: 'get',
        })
        .then((res) => {
          //获取当前页的数据
          tableData.value = res.data.data.rows
          //获取总记录数
          totalCount.value = res.data.data.count
          loading.value = false
        })
        .catch((e) => {
          console.log(e)
        })
    }
    getData()
    // 查询操作
    const handleSearch = () => {
      getData()
    }
    // 分页导航
    const handleCurrentChange = (val) => {
      loading.value = true
      query.currentPage = val
      getData()
    }
    const selectArray = ref('')
    //选中
    const handleSelect = (val) => {
      selectArray.value = []
      for (const iterator of val) {
        selectArray.value.push(iterator.foodId)
      }
    }
    //删除全部选中
    const deleteAll = () => {
      loading.value = true
      JSON.stringify(selectArray.value)
      request
        .request({
          url: '/food/deleteFood',
          method: 'get',
          params: {
            foodIds: selectArray.value,
          },
          paramsSerializer: (params) => {
            return qs.stringify(params, { indices: false })
          },
        })
        .then((res) => {
          if (res.data.message == 'success') {
            getData()

            ElNotification({
              title: '删除成功',
              message: '成功删除食物信息',
            })
          } else {
            ElNotification({
              title: '删除失败',
              message: '请联系管理员检查失败原因',
            })
          }
        })
        .catch((e) => {
          ElNotification({
            title: '删除失败',
            message: '请联系管理员检查失败原因',
          })
        })
    }
    // 删除操作
    const handleDelete = (index, row) => {
      loading.value = true
      request
        .request({
          url: '/food/deleteFood?foodIds=' + row.foodId,
          method: 'get',
          params: {
            foodId: row.foodId,
          },
        })
        .then((res) => {
          if (res.data.message == 'success') {
            getData()

            ElNotification({
              title: '删除成功',
              message: '成功删除食物信息',
            })
          } else {
            ElNotification({
              title: '删除失败',
              message: '请联系管理员检查失败原因',
            })
          }
        })
        .catch((e) => {
          ElNotification({
            title: '删除失败',
            message: '请联系管理员检查失败原因',
          })
        })
    }
    // 获取文件数据
    const imageUrl = ref('')
    const selectedFile = ref()
    const handelFileChange = (file) => {
      selectedFile.value = file.raw
      imageUrl.value = URL.createObjectURL(file.raw)
    }
    const handleEdit = (index, row) => {
      sessionStorage.setItem(row.foodId, JSON.stringify(row))
      router.push({
        name: 'foodEdit',
        query: {
          foodId: row.foodId,
        },
      })
    }
    //添加食物
    const handleAdd = () => {
      router.push('foodAdd')
    }

    //定义一个响应式数组用来接收图片
    const fileList = ref([])

    //自定义函数用来覆盖原有的XHR行为（默认提交行为）
    function httpRequest(option) {
      //将图片存到数组中
      fileList.value.push(option)
    }

    const handleCategory = (list) => {
      const name = ref('')
      switch (list) {
        case 0:
          name.value = '其他'
          break
        case 1:
          name.value = '谷类及制品'
          break
        case 2:
          name.value = '薯类、淀粉及制品'
          break
        case 3:
          name.value = '干豆类及制品'
          break
        case 4:
          name.value = '蔬菜类及制品'
          break
        case 5:
          name.value = '菌藻类'
          break
        case 6:
          name.value = '水果类及制品'
          break
        case 7:
          name.value = '坚果、种子类'
          break
        case 8:
          name.value = '植物油'
          break
        case 9:
          name.value = '畜肉类及制品'
          break
        case 10:
          name.value = '禽肉类及制品'
          break
        case 11:
          name.value = '乳类及制品'
          break
        case 12:
          name.value = '蛋类及制品'
          break
        case 13:
          name.value = '鱼虾蟹贝类'
          break
        case 14:
          name.value = '油脂'
          break
        case 15:
          name.value = '婴幼儿食品'
          break
        case 16:
          name.value = '小吃、甜饼'
          break
        case 17:
          name.value = '速食食品'
          break
        case 18:
          name.value = '饮料类'
          break
        case 19:
          name.value = '含酒精饮料'
          break
        case 20:
          name.value = '糖、果脯和蜜饯、蜂蜜类'
          break
        case 21:
          name.value = '调味品类'
          break
        default:
          name.value = '其他'
      }
      return name.value
    }

    const tagType = (val) => {
      if (parseFloat(val)&&parseFloat(val)!=0) {
        if(parseFloat(val)>0 && parseFloat(val)<55){
          return 'success'
        }else if(parseFloat(val)>=55 && parseFloat(val)<=70){
          return 'warning'
        }else{
          return 'danger'
        }
      }else{
        if(parseFloat(val)==0){
          return 'success'
        }else{
          return 'info'
        }
      }
    }
    const tagValue = (val) => {
      if (val) {
        if (val < 55) {
          return '低GI食物'
        } else if (55 <= val <= 70) {
          return '中等GI食物'
        } else {
          return '高GI食物'
        }
      } else {
        return '无'
      }
    }
    const handleAddAll = () => {
      router.push('foodAddAll')
    }
    return {
      loading,
      resetForm,
      ruleFormRef,
      submitForm,
      ruleForm,
      centerDialogVisible,
      query,
      totalCount,
      tableData,
      getData,
      handleEdit,
      handleSearch,
      handleCurrentChange,
      handleDelete,
      handleSelect,
      selectArray,
      deleteAll,
      fileList,
      httpRequest,
      handelFileChange,
      selectedFile,
      processFormData,
      handleAdd,
      imageUrl,
      handleCategory,
      tagType,
      tagValue,
      typeList,
      handleAddAll,
    }
  },
}
</script>
<style lang="scss" scoped>
.handle-box {
  margin-bottom: 20px;
}

.handle-select {
  width: 120px;
}

.handle-input {
  width: 300px;
  display: inline-block;
}

.table {
  width: 100%;
  font-size: 14px;
}

.mr10 {
  margin-right: 10px;
}
</style>
